/**
 * BackgroundManager - 背景管理器
 * 管理多个背景层、主题切换和视差效果
 */

import { Background, type BackgroundOptions } from './Background'


export interface BackgroundLayer {
  /** 背景实体 */
  background: Background
  /** 层级名称 */
  name: string
  /** 是否启用 */
  enabled: boolean
}

export interface ThemeConfig {
  /** 主题名称 */
  name: string
  /** 主题显示名称 */
  displayName: string
  /** 背景层配置 */
  layers: Array<{
    name: string
    imagePath?: string
    color?: string
    scrollSpeed: number
    parallaxLayer: number
    opacity?: number
    repeat?: boolean
    width: number
    height: number
    y?: number
  }>
  /** 主题音乐路径 */
  musicPath?: string
}

export interface BackgroundManagerOptions {
  /** Canvas宽度 */
  canvasWidth: number
  /** Canvas高度 */
  canvasHeight: number
  /** 默认主题 */
  defaultTheme?: string
}

/**
 * 背景管理器类
 * 负责管理多层背景、主题切换和视差滚动效果
 */
export class BackgroundManager {
  private layers: Map<string, BackgroundLayer> = new Map()
  private currentTheme: string = ''
  private canvasWidth: number
  private canvasHeight: number
  private themes: Map<string, ThemeConfig> = new Map()
  private globalScrollSpeed: number = 1.0
  private isTransitioning: boolean = false
  private transitionProgress: number = 0

  constructor(options: BackgroundManagerOptions) {
    this.canvasWidth = options.canvasWidth
    this.canvasHeight = options.canvasHeight
    
    // 初始化默认主题
    this.initializeDefaultThemes()
    
    if (options.defaultTheme) {
      this.setTheme(options.defaultTheme)
    }
  }

  /**
   * 初始化默认主题配置
   */
  private initializeDefaultThemes(): void {
    // 城市主题
    this.addTheme({
      name: 'city',
      displayName: '城市',
      layers: [
        {
          name: 'sky',
          color: '#87CEEB',
          scrollSpeed: 50,
          parallaxLayer: 8,
          opacity: 1.0,
          repeat: true,
          width: this.canvasWidth,
          height: this.canvasHeight,
          y: 0
        },
        {
          name: 'buildings_far',
          color: '#696969',
          scrollSpeed: 100,
          parallaxLayer: 6,
          opacity: 0.7,
          repeat: true,
          width: this.canvasWidth * 1.5,
          height: this.canvasHeight * 0.6,
          y: this.canvasHeight * 0.4
        },
        {
          name: 'buildings_near',
          color: '#2F4F4F',
          scrollSpeed: 150,
          parallaxLayer: 3,
          opacity: 0.8,
          repeat: true,
          width: this.canvasWidth * 1.2,
          height: this.canvasHeight * 0.8,
          y: this.canvasHeight * 0.2
        },
        {
          name: 'ground',
          color: '#708090',
          scrollSpeed: 200,
          parallaxLayer: 1,
          opacity: 1.0,
          repeat: true,
          width: this.canvasWidth,
          height: this.canvasHeight * 0.1,
          y: this.canvasHeight * 0.9
        }
      ]
    })

    // 森林主题
    this.addTheme({
      name: 'forest',
      displayName: '森林',
      layers: [
        {
          name: 'sky',
          color: '#87CEEB',
          scrollSpeed: 30,
          parallaxLayer: 10,
          opacity: 1.0,
          repeat: true,
          width: this.canvasWidth,
          height: this.canvasHeight,
          y: 0
        },
        {
          name: 'mountains',
          color: '#8FBC8F',
          scrollSpeed: 60,
          parallaxLayer: 8,
          opacity: 0.6,
          repeat: true,
          width: this.canvasWidth * 1.5,
          height: this.canvasHeight * 0.4,
          y: this.canvasHeight * 0.3
        },
        {
          name: 'trees_far',
          color: '#228B22',
          scrollSpeed: 100,
          parallaxLayer: 5,
          opacity: 0.7,
          repeat: true,
          width: this.canvasWidth * 1.3,
          height: this.canvasHeight * 0.6,
          y: this.canvasHeight * 0.4
        },
        {
          name: 'trees_near',
          color: '#006400',
          scrollSpeed: 150,
          parallaxLayer: 2,
          opacity: 0.9,
          repeat: true,
          width: this.canvasWidth * 1.1,
          height: this.canvasHeight * 0.7,
          y: this.canvasHeight * 0.3
        },
        {
          name: 'ground',
          color: '#8B4513',
          scrollSpeed: 200,
          parallaxLayer: 1,
          opacity: 1.0,
          repeat: true,
          width: this.canvasWidth,
          height: this.canvasHeight * 0.1,
          y: this.canvasHeight * 0.9
        }
      ]
    })

    // 沙漠主题
    this.addTheme({
      name: 'desert',
      displayName: '沙漠',
      layers: [
        {
          name: 'sky',
          color: '#FFE4B5',
          scrollSpeed: 40,
          parallaxLayer: 12,
          opacity: 1.0,
          repeat: true,
          width: this.canvasWidth,
          height: this.canvasHeight,
          y: 0
        },
        {
          name: 'dunes_far',
          color: '#F4A460',
          scrollSpeed: 70,
          parallaxLayer: 7,
          opacity: 0.5,
          repeat: true,
          width: this.canvasWidth * 1.4,
          height: this.canvasHeight * 0.3,
          y: this.canvasHeight * 0.5
        },
        {
          name: 'dunes_near',
          color: '#D2691E',
          scrollSpeed: 120,
          parallaxLayer: 3,
          opacity: 0.8,
          repeat: true,
          width: this.canvasWidth * 1.2,
          height: this.canvasHeight * 0.5,
          y: this.canvasHeight * 0.5
        },
        {
          name: 'sand',
          color: '#F5DEB3',
          scrollSpeed: 180,
          parallaxLayer: 1,
          opacity: 1.0,
          repeat: true,
          width: this.canvasWidth,
          height: this.canvasHeight * 0.1,
          y: this.canvasHeight * 0.9
        }
      ]
    })
  }

  /**
   * 添加主题配置
   */
  addTheme(theme: ThemeConfig): void {
    this.themes.set(theme.name, theme)
  }

  /**
   * 设置当前主题
   */
  setTheme(themeName: string): void {
    const theme = this.themes.get(themeName)
    if (!theme) {
      console.warn(`Theme "${themeName}" not found`)
      return
    }

    this.currentTheme = themeName
    this.createBackgroundLayers(theme)
  }

  /**
   * 创建背景层
   */
  private createBackgroundLayers(theme: ThemeConfig): void {
    // 清除现有层
    this.layers.clear()

    // 创建新的背景层
    theme.layers.forEach(layerConfig => {
      const backgroundOptions: BackgroundOptions = {
        x: 0,
        y: layerConfig.y || 0,
        width: layerConfig.width,
        height: layerConfig.height,
        scrollSpeed: layerConfig.scrollSpeed * this.globalScrollSpeed,
        repeat: layerConfig.repeat ?? true,
        parallaxLayer: layerConfig.parallaxLayer,
        opacity: layerConfig.opacity ?? 1.0
      }

      // 如果有图像路径，创建精灵
      if (layerConfig.imagePath) {
        // TODO: 实现图像加载
        // backgroundOptions.sprite = await this.loadSprite(layerConfig.imagePath)
      }

      const background = new Background(backgroundOptions)
      
      // 如果没有图像，设置颜色
      if (layerConfig.color && !layerConfig.imagePath) {
        background.sprite = null
        // 创建一个自定义背景类来处理颜色
        const customBackground = background as any
        customBackground._customColor = layerConfig.color
      }

      const layer: BackgroundLayer = {
        background,
        name: layerConfig.name,
        enabled: true
      }

      this.layers.set(layerConfig.name, layer)
    })
  }

  /**
   * 平滑切换主题
   */
  async switchTheme(themeName: string, duration: number = 2000): Promise<void> {
    if (this.isTransitioning) {
      console.warn('Theme transition already in progress')
      return
    }

    const theme = this.themes.get(themeName)
    if (!theme) {
      console.warn(`Theme "${themeName}" not found`)
      return
    }

    this.isTransitioning = true
    this.transitionProgress = 0

    // 创建新主题的背景层（暂时隐藏）
    const oldLayers = new Map(this.layers)
    this.currentTheme = themeName
    this.createBackgroundLayers(theme)
    
    // 设置新层的初始透明度为0
    this.layers.forEach(layer => {
      layer.background.setOpacity(0)
    })

    // 执行过渡动画
    return new Promise(resolve => {
      const startTime = performance.now()
      
      const animate = (currentTime: number) => {
        const elapsed = currentTime - startTime
        this.transitionProgress = Math.min(elapsed / duration, 1)

        // 更新透明度
        const fadeOutOpacity = 1 - this.transitionProgress
        const fadeInOpacity = this.transitionProgress

        // 淡出旧层
        oldLayers.forEach(layer => {
          layer.background.setOpacity(fadeOutOpacity)
        })

        // 淡入新层
        this.layers.forEach(layer => {
          layer.background.setOpacity(fadeInOpacity)
        })

        if (this.transitionProgress < 1) {
          requestAnimationFrame(animate)
        } else {
          // 过渡完成
          this.isTransitioning = false
          this.transitionProgress = 0
          
          // 清理旧层
          oldLayers.forEach(layer => {
            layer.background.destroy()
          })
          
          resolve()
        }
      }

      requestAnimationFrame(animate)
    })
  }

  /**
   * 更新所有背景层
   */
  update(deltaTime: number): void {
    this.layers.forEach(layer => {
      if (layer.enabled) {
        layer.background.update(deltaTime)
      }
    })
  }

  /**
   * 渲染所有背景层
   */
  render(ctx: CanvasRenderingContext2D): void {
    // 按视差层级排序（层级越高越先渲染）
    const sortedLayers = Array.from(this.layers.values())
      .filter(layer => layer.enabled)
      .sort((a, b) => b.background.parallaxLayer - a.background.parallaxLayer)

    sortedLayers.forEach(layer => {
      layer.background.render(ctx)
    })
  }

  /**
   * 设置全局滚动速度
   */
  setGlobalScrollSpeed(speed: number): void {
    const oldGlobalSpeed = this.globalScrollSpeed
    this.globalScrollSpeed = Math.max(0, speed)
    
    // 更新所有背景层的滚动速度
    this.layers.forEach(layer => {
      const originalSpeed = layer.background.scrollSpeed / oldGlobalSpeed
      layer.background.setScrollSpeed(originalSpeed * this.globalScrollSpeed)
    })
  }

  /**
   * 获取当前主题名称
   */
  getCurrentTheme(): string {
    return this.currentTheme
  }

  /**
   * 获取所有可用主题
   */
  getAvailableThemes(): ThemeConfig[] {
    return Array.from(this.themes.values())
  }

  /**
   * 启用/禁用背景层
   */
  setLayerEnabled(layerName: string, enabled: boolean): void {
    const layer = this.layers.get(layerName)
    if (layer) {
      layer.enabled = enabled
    }
  }

  /**
   * 获取背景层
   */
  getLayer(layerName: string): BackgroundLayer | undefined {
    return this.layers.get(layerName)
  }

  /**
   * 重置所有背景层位置
   */
  reset(): void {
    this.layers.forEach(layer => {
      layer.background.reset()
    })
  }

  /**
   * 清理资源
   */
  cleanup(): void {
    this.layers.forEach(layer => {
      layer.background.destroy()
    })
    this.layers.clear()
    this.themes.clear()
  }
}